package org.lgiavedoni.android.franq.service.phone.calendar.dao.imp;

import java.util.ArrayList;
import java.util.List;

import org.lgiavedoni.android.franq.core.calendar.Calendar;
import org.lgiavedoni.android.franq.core.calendar.CalendarEvent;
import org.lgiavedoni.android.franq.core.calendar.CalendarImp;
import org.lgiavedoni.android.franq.service.log.Logger;
import org.lgiavedoni.android.franq.service.phone.ContextService;
import org.lgiavedoni.android.franq.service.phone.calendar.dao.CalendarDAO;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class CalendarLocalDAO implements CalendarDAO {

	@Override
	public List<Calendar> getAllCalendars() {
		List<Calendar> calendars = new ArrayList<Calendar>();
		String[] projection = new String[] { "_id", "name" };
		Uri calendarsURI = Uri.parse("content://calendar/calendars");
		ContentResolver cr = ContextService.inst.getApplicationContext().getContentResolver();

		Cursor managedCursor = cr.query(calendarsURI, projection, "selected=1", null, null);

		String calName;
		String calId = null;

		if (managedCursor.moveToFirst()) {

			int nameColumn = managedCursor.getColumnIndex("name");
			int idColumn = managedCursor.getColumnIndex("_id");
			do {
				calId = managedCursor.getString(idColumn);
				calName = managedCursor.getString(nameColumn);
				calendars.add(new CalendarImp(calId, calName));
			} while (managedCursor.moveToNext());
		}
		return calendars;
	}

	public void addEvent(Calendar calendar, CalendarEvent event) {
		if (!ContextService.inst.isApplicationContextLoaded())
			return;

		ContentResolver cr = ContextService.inst.getApplicationContext().getContentResolver();
		ContentValues eventvalues = new ContentValues();
		// FIXME
		eventvalues.put("calendar_id", ((CalendarImp) calendar).getId());
		eventvalues.put("title", event.getTitle());
		eventvalues.put("description", event.getDescription());
		eventvalues.put("eventLocation", "TBD");
		eventvalues.put("dtstart", event.getStartDate().getTime());
		eventvalues.put("dtend", event.getEndDate().getTime());
		Uri eventsUri = Uri.parse("content://calendar/events");
		cr.insert(eventsUri, eventvalues);
	}

	@Override
	public Calendar createCalendar(String title) {
		Logger.inst.error("CalendarLocalDAO.createCalendar NOT implemented yet");
		return null;
	}

	@Override
	public List<CalendarEvent> getAllCalendarEntryes(Calendar calendar) {
		throw new RuntimeException("CalendarLocalDAO.getAllCalendarEntryes not implemented yet");
		// return null;
	}

	@Override
	public List<CalendarEvent> getFutureCalendarEntryes(Calendar calendar) {
		throw new RuntimeException("CalendarLocalDAO.getFutureCalendarEntryes not implemented yet");
	}

	public void removeEvent(CalendarEvent event) {
		throw new RuntimeException("CalendarLocalDAO.removeEvent not implemented yet");
	}

}
